#include "state_machine/double_buffer/state_machine.h"

#include <chrono>
#include <ctime>
#include <iostream>
#include <thread>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>

TaskNode current_task;
std::deque<TaskNode> new_tasks;
std::deque<Event> event_queue;
std::mutex mtx;
std::atomic<bool> is_running(true);
std::atomic<bool> all_tasks_processed(false);
std::stack<TaskNode> task_history;

// 获取易读的任务名称
std::string getTaskName(TaskNode::TaskType id)
{
    switch (id)
    {
        case TaskNode::TaskType::PATH_PLANNING:
            return "路径规划";
        case TaskNode::TaskType::BRAKE:
            return "制动";
        case TaskNode::TaskType::STEERING:
            return "转向";
        default:
            return "未知任务";
    }
}

// 获取优先级文本
std::string getPriorityText(Priority p)
{
    switch (p)
    {
        case Priority::LOW:
            return "低";
        case Priority::MEDIUM:
            return "中";
        case Priority::HIGH:
            return "高";
        default:
            return "未知";
    }
}

std::string getEventTypeName(Event::Type type)
{
    switch (type)
    {
        case Event::Type::PATH_UPDATE:
            return "路径更新";
        case Event::Type::OBSTACLE_DETECTED:
            return "障碍检测";
        case Event::Type::EMERGENCY_STOP:
            return "紧急制动";
        default:
            return "未知事件";
    }
}

// 获取微秒级时间戳
uint64_t getMicrosecondTimestamp()
{
    return std::chrono::duration_cast<std::chrono::microseconds>(
               std::chrono::high_resolution_clock::now().time_since_epoch())
        .count();
}

// 【新增埋点2：模拟IO密集型操作（频繁写入小文件）】
// 【改造后的IO埋点2：显著增加IO开销】
void simulate_io_heavy(int num_files) {
    for (int i = 0; i < num_files; ++i) {
        char filename[64];
        snprintf(filename, sizeof(filename), "temp_io_%d_%llu.txt", i, 
                 (unsigned long long)getMicrosecondTimestamp());
        
        // 用C的open函数打开文件，直接获取文件描述符（fd）
        int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
        if (fd != -1) {  // 打开成功
            // 写入100KB无意义数据（每次写1KB，重复100次）
            char dummy[1024];
            memset(dummy, 'a', 1024);  // 填充数据
            for (int j = 0; j < 100; ++j) {
                write(fd, dummy, 1024);  // 用C的write函数写入
            }
            
            fsync(fd);  // 直接用文件描述符调用fsync，强制刷盘（关键）
            close(fd);  // 关闭文件
        }
        
        // 删除文件
        remove(filename);
    }
}

void init_tasks_interface()
{
    std::lock_guard<std::mutex> lock(mtx);

    current_task = {TaskNode::TaskType::PATH_PLANNING,
                    getMicrosecondTimestamp(),
                    Status::RUNNING,
                    Priority::LOW,
                    "初始路径规划",
                    true,
                    "系统初始化"};
    new_tasks.clear();
    event_queue.clear();
    while (!task_history.empty()) task_history.pop();
}

TaskNode execute_task(TaskNode task)
{
    const int total_sec = 10;  // 总耗时5秒，对应100%进度
    task.status = Status::RUNNING;
    std::cout << "[执行] " << getTaskName(task.task_type) << " | uid: " << task.uid
              << " | 总耗时: " << total_sec << "秒 | 从当前进度继续: " << task.context.progress
              << "%" << std::endl;

    int elapsed_sec = (total_sec * task.context.progress) / 100;
    int remaining_sec = total_sec - elapsed_sec;

    // 【埋坑1：每次进度更新前做大量无意义计算（CPU密集）】
    auto waste_cpu = [](int n) {
        int sum = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < 100000; ++j) {  // 循环100万次，纯耗CPU
                sum += (i * j) % 12345;  // 无意义计算
            }
        }
        return sum;
    };

    // 按1秒为单位分片执行，每1秒更新一次进度
    for (int i = 0; i < remaining_sec; ++i)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        elapsed_sec += 1;
        task.context.progress = (elapsed_sec * 100) / total_sec;

        waste_cpu(1000000);  // 埋坑1：每次进度更新前做大量无意义计算（CPU密集）

        if (task.status == Status::PAUSED)
        {
            std::cout << "[暂停] 任务在" << task.context.progress << "%进度处暂停" << std::endl;
            return task;
        }

        std::cout << "[进度] " << getTaskName(task.task_type) << " | uid: " << task.uid
                  << " | 当前进度: " << task.context.progress << "%" << std::endl;
    }

    // 任务完成，进度设为100%
    task.context.progress = 100;
    task.status = Status::COMPLETED;
    std::cout << "[完成] " << getTaskName(task.task_type) << " uid: " << task.uid
              << "| 总耗时: " << total_sec << "秒 | 最终进度: 100%" << std::endl;

    return task;
}

void schedule_next_task()
{
    if (!new_tasks.empty())
    {
        task_history.push(current_task);   // 保存旧任务
        current_task = new_tasks.front();  // 切换到新任务
        new_tasks.pop_front();
        std::cout << "[调度] 准备执行新任务: " << getTaskName(current_task.task_type) << std::endl;
    }
    else
    {
        std::cout << "[调度] 任务队列为空" << std::endl;
    }
}

void pause_current_task()
{
    if (current_task.status == Status::RUNNING)
    {
        current_task.status = Status::PAUSED;
        std::cout << "[暂停] " << getTaskName(current_task.task_type)
                  << " | uid: " << current_task.uid << " | 状态: 已暂停" << std::endl;
    }
}

void rollback_task_interface()
{
    std::lock_guard<std::mutex> lock(mtx);

    if (task_history.empty())
    {
        std::cout << "[回滚] 无历史任务可回滚" << std::endl;
        return;
    }

    // 弹出上一个任务作为回滚目标
    TaskNode prev_task = task_history.top();
    task_history.pop();

    std::cout << "[回滚] 从" << getTaskName(current_task.task_type) << "回退到"
              << getTaskName(prev_task.task_type) << std::endl;

    // 暂停当前任务并保存到历史（支持再次回滚）
    pause_current_task();
    task_history.push(current_task);

    // 恢复历史任务及其上下文
    current_task = prev_task;
    if (current_task.status == Status::PAUSED)
    {
        current_task.status = Status::RUNNING;
    }
    TaskNode task = execute_task(current_task);  // 若未完成，从上下文进度续跑
    current_task = task;
}

void process_event_interface(const Event& event)
{
    std::cout << "\n=== 事件处理开始 ===" << std::endl;
    std::cout << "[新事件] 类型: " << getEventTypeName(event.type) << " | 描述: " << event.desc
              << " | 优先级: " << getPriorityText(event.priority) << std::endl;

    // [启用/禁用IO埋点：每次处理事件前执行IO密集操作]
    // simulate_io_heavy(10);  // 埋点2：创建10个临时文件并写入数据（IO密集）

    TaskNode tmp_task;
    bool need_schedule = false;

    {
        std::lock_guard<std::mutex> lock(mtx);

        // 移除可取消任务
        std::deque<TaskNode> temp_queue;
        while (!new_tasks.empty())
        {
            TaskNode task = new_tasks.front();
            new_tasks.pop_front();
            if (!task.is_cancellable)
            {
                temp_queue.push_back(task);
            }
            else
            {
                std::cout << "[移除] id: " << getTaskName(task.task_type) << " | uid: " << task.uid
                          << " | 参数: " << task.param
                          << " | 优先级: " << getPriorityText(task.priority)
                          << " | 来源: " << task.eventName << std::endl;
            }
        }
        new_tasks = temp_queue;
        // 根据任务类型添加新任务
        switch (event.type)
        {
            case Event::Type::EMERGENCY_STOP:
                new_tasks.push_back({TaskNode::TaskType::BRAKE, getMicrosecondTimestamp(),
                                     Status::PENDING, Priority::HIGH, "全力制动",
                                     false /* 紧急制动不可取消 */, event.desc});
                break;
            case Event::Type::PATH_UPDATE:
                new_tasks.push_back({TaskNode::TaskType::PATH_PLANNING, getMicrosecondTimestamp(),
                                     Status::PENDING, Priority::LOW, "新路径参数", true,
                                     event.desc});
                break;
            case Event::Type::OBSTACLE_DETECTED:  // 避障是2个任务
                new_tasks.push_back({TaskNode::TaskType::BRAKE, getMicrosecondTimestamp(),
                                     Status::PENDING, Priority::MEDIUM, "减速50%", true,
                                     event.desc});
                new_tasks.push_back({TaskNode::TaskType::STEERING, getMicrosecondTimestamp(),
                                     Status::PENDING, Priority::MEDIUM, "转向30度", true,
                                     event.desc});
                break;
        }

        // 打印待执行任务队列
        std::cout << "[队列] 待执行任务 (" << new_tasks.size() << "个):" << std::endl;
        for (size_t i = 0; i < new_tasks.size(); ++i)
        {
            std::cout << "  " << i + 1 << ". " << getTaskName(new_tasks[i].task_type)
                      << " | uid: " << new_tasks[i].uid << " | 参数: " << new_tasks[i].param
                      << " | 优先级: " << getPriorityText(new_tasks[i].priority)
                      << " | 来源: " << new_tasks[i].eventName << std::endl;
        }

        // 打印当前任务
        if (current_task.status != Status::COMPLETED)
        {
            // 任务切换判断
            std::cout << "[当前] " << getTaskName(current_task.task_type)
                      << " | uid: " << current_task.uid << " | 状态: "
                      << (current_task.status == Status::RUNNING
                              ? "运行中"
                              : (current_task.status == Status::COMPLETED ? "已完成" : "已暂停"))
                      << " | 优先级: " << getPriorityText(current_task.priority) << std::endl;
        }
        else
        {
            std::cout << "[当前] 无运行中任务" << std::endl;
        }

        if ((!new_tasks.empty() && new_tasks.front().priority >= current_task.priority) ||
            (!new_tasks.empty() && current_task.status == Status::COMPLETED))  // 特殊情况
        {
            if (current_task.status != Status::COMPLETED)
            {
                std::cout << "[决策] 允许任务切换" << std::endl;
                pause_current_task();
            }
            schedule_next_task();
            need_schedule = true;
            tmp_task = current_task;
            // TaskNode task = execute_task(tmp_task);  // 若未完成，从上下文进度续跑
            // current_task = task;
        }
        else if (new_tasks.empty())
        {
            std::cout << "[决策] 无待执行任务" << std::endl;
        }
        else
        {
            std::cout << "[决策] 保持当前任务" << std::endl;
        }
    }

    if (need_schedule)
    {
        std::lock_guard<std::mutex> lock(mtx);
        TaskNode task = execute_task(tmp_task);  // 若未完成，从上下文进度续跑
        current_task = task;
    }

    std::cout << "=== 事件处理结束 ===\n" << std::endl;
}

void post_event_interface(const Event& event)
{
    std::lock_guard<std::mutex> lock(mtx);
    event_queue.push_back(event);
    std::cout << "[投递事件] 类型: " << getEventTypeName(event.type) << "（已加入队列）"
              << std::endl;
}

void event_processing_loop_interface()
{
    while (is_running)
    {
        Event event;
        bool has_event = false;
        {
            std::lock_guard<std::mutex> lock(mtx);
            if (!event_queue.empty())
            {
                event = event_queue.front();
                event_queue.pop_front();
                has_event = true;
            }
        }

        if (has_event)
            process_event_interface(event);
        else
        {
            {
                std::lock_guard<std::mutex> lock(mtx);
                if (new_tasks.empty() && current_task.status == Status::COMPLETED)
                {
                    all_tasks_processed = true;
                }
            }

            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
    }
}